//获取网页的 url 的 id 参数   方式一
// let url = new URL(location.href);
// console.log(url);
// let id = url.searchParams.get('id');
  
//提取 URL 的 query 参数      方式二
import qs from 'qs';
import axios from 'axios';
import moment from 'moment';
import swal from 'sweetalert';

let {id} = qs.parse(location.search.slice(1));

//获取 token
let token = localStorage.getItem('token');
if(!token){
  location.href = '/login.html';
}

//发送 AJAX 请求
(async () => {
  //发送请求
  let result = await axios.get(`http://127.0.0.1:3001/api/account/${id}`, {
    headers: {
      token: token
    }
  });
  //设置标题
  document.querySelector('input[name=title]').value=result.data.data.title;
  //设置时间
  document.querySelector('input[name=date]').value=moment(result.data.data.date).format('YYYY-MM-DD');
  //设置类型
  document.querySelector('select[name=type]').value = result.data.data.type;
  //设置金额
  document.querySelector('input[name=money]').value= result.data.data.money;
  //设置备注
  document.querySelector('textarea').value = result.data.data.note;
})();

(async () => {
  //获取提交按钮
  let btn = document.querySelector('button[type=submit]');
  //获取表单元素
  let form = document.querySelector('form');
  //绑定单击事件
  btn.onclick = async function(e){
    //阻止默认行为
    e.preventDefault();
    //获取表单数据
    let formdata = new FormData(form);
    //将 formdata 数据转为 querystring
    const queryString = new URLSearchParams(formdata).toString();
    //发送 AJAX 请求
    let result = await axios.patch(`http://127.0.0.1:3001/api/account/${id}`, queryString, {
      headers: {
        token: token
      }
    });
    //判断
    if(result.data.code==='0000'){
      //登录成功之后, 跳转账单的列表页
      swal({
        title: "温馨提示",
        text: "更新成功",
        icon: "success",
        buttons: true,
        dangerMode: false,
      }).then(() => {
        //跳转
        location.href = '/accounts.html';
      })
    }else{
      swal({
        title: "温馨提示",
        text: "更新失败",
        icon: "error",
        dangerMode: true,
      })
    }
  }
})();



